// Copyright (C) Kumo inc. and its affiliates.
// Author: Jeff.li lijippy@163.com
// All rights reserved.
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <https://www.gnu.org/licenses/>.
//

#pragma once

#include <memory>
#include <utility>
#include <vector>

#include <nebula/io/interfaces.h>
#include <nebula/future/thread_pool.h>
#include <nebula/util/type_fwd.h>
#include <turbo/base/macros.h>

namespace nebula::io::internal {

    TURBO_EXPORT void CloseFromDestructor(FileInterface *file);

    // Validate a (offset, size) region (as given to read_at) against
    // the file size.  Return the actual read size.
    TURBO_EXPORT turbo::Result<int64_t> ValidateReadRange(int64_t offset, int64_t size,
                                                   int64_t file_size);
    // Validate a (offset, size) region (as given to write_at) against
    // the file size.  Short writes are not allowed.
    TURBO_EXPORT turbo::Status ValidateWriteRange(int64_t offset, int64_t size, int64_t file_size);

    // Validate a (offset, size) region (as given to read_at or write_at), without
    // knowing the file size.
    TURBO_EXPORT turbo::Status ValidateRange(int64_t offset, int64_t size);

    TURBO_EXPORT
    turbo::Result<std::vector<ReadRange>> CoalesceReadRanges(std::vector<ReadRange> ranges,
                                                      int64_t hole_size_limit,
                                                      int64_t range_size_limit);

    TURBO_EXPORT
    ::nebula::internal::ThreadPool *GetIOThreadPool();

    template<typename... SubmitArgs>
    auto SubmitIO(IOContext io_context, SubmitArgs &&... submit_args)
    -> decltype(std::declval<::nebula::internal::Executor *>()->submit(submit_args...)) {
        ::nebula::internal::TaskHints hints;
        hints.external_id = io_context.external_id();
        return io_context.executor()->submit(hints, io_context.stop_token(),
                                             std::forward<SubmitArgs>(submit_args)...);
    }

}  // namespace nebula::io::internal

